<template>
    <div class="app-container">
        <el-form ref="form" :model="params">
            <div class="params-form params-form-gray">
                <el-form-item label="借款ID">
                    <el-input v-model="params.billNoteId" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="关键词">
                    <el-input v-model="params.description" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="创建时间">
                    <el-date-picker v-model="params.date" type="daterange" start-placeholder="开始时间"
                        end-placeholder="结束时间" value-format="YYYY-MM-DD" />
                </el-form-item>
                <el-form-item label="创建人">
                    <el-input v-model="params.createUser" placeholder="请输入" style="flex: 1;" @keyup.enter="init"
                        @blur="init" />
                </el-form-item>
                <el-form-item>
                    <el-button :icon="Search" type="primary" @click="init">查询</el-button>
                    <el-button :icon="RefreshRight" plain type="primary" @click="reset">重置</el-button>
                </el-form-item>
            </div>
        </el-form>
        <div class="table-add">
            <el-space>
                <el-button type="primary" @click="excel">导出</el-button>
            </el-space>
            <el-space><el-checkbox v-model="params.overdue" @change="init"></el-checkbox>超期未还款</el-space>
        </div>
        <div class="table">
            <el-table :data="data" style="width: 100%" max-height="calc(100vh - 400px)">
                <el-table-column prop="billNoteId" label="借款ID" width="160" />
                <el-table-column prop="businessType" label="描述" width="300"  >
                    <template #default="scope">
                        <div class="desc">
                        {{scope.row.description}}
                    </div>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" min-width="200" />
                <el-table-column prop="createBy" label="创建人" width="120"/>
                <el-table-column prop="money" label="借款金额" width="120"/>
                <el-table-column prop="address" label="预计还款日期" width="120">
                    <template #default="scope">
                        <div :class="{ overdue: scope.row.overdue }">{{ scope.row.repaymentDate }}</div>
                    </template>
                </el-table-column>
                <el-table-column label="收款账户" width="200">
                    <template #default="scope">
                        <div class="desc">{{ scope.row.payName}}{{ scope.row.account?'-'+scope.row.account:'' }}{{ scope.row.accountName?'-'+scope.row.accountName:''  }}</div>
                    </template>
                </el-table-column>
                <el-table-column prop="addDate" label="付款状态" width="180">
                    <template #default="scope">
                        <el-tag :type="statusList[scope.row.status]">{{ scope.row.status }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="remark" label="还款状态" width="180">
                    <template #default="scope">
                        <el-tag :type="statusList[scope.row.repaymentStatus]" v-if="scope.row.repaymentStatus">{{
            scope.row.repaymentStatus }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" fixed="right" width="130">
                    <template #default="scope">
                        <el-button type="primary" link @click="openDrawer(scope.row)">详情</el-button>
                    </template>
                </el-table-column>
                <template #empty>
                    <el-empty />
                </template>
            </el-table>
        </div>
        <div class="pagination">
            <el-pagination v-model:current-page="query.current" v-model:page-size="query.size"
                :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="total"
                @size-change="init" @current-change="init" />
        </div>
        <el-drawer v-model="visible" :with-header="false" @close="close">
            <div class="drawer-content">
                <div class="title-box">
                    <custom-title :title="isNew ? '新建借款单' : '借款单详情'" />
                    <el-icon @click="visible = false">
                        <Close />
                    </el-icon>
                </div>
                <div :class="{ 'params-form-gray': !isNew }" v-if="visible">
                    <el-form :model="addForm" ref="addFormRef" :rules="isNew ? rules : {}" label-width="auto">
                        <el-form-item label="借款分类" prop="billCategoryId">
                            <div class="preview">{{ addForm.billCategoryName }}</div>
                        </el-form-item>
                        <el-form-item label="借款金额" prop="money">
                            <div class="preview">{{ addForm.money }}</div>
                        </el-form-item>
                        <el-form-item label="预计还款日期" prop="repaymentDate">
                            <div class="preview">{{ addForm.repaymentDate }}</div>
                        </el-form-item>
                        <el-form-item label="支付账号" prop="partnerAccountId">
                            <div class="form-item-space">
                                <div class="preview">{{ addForm.account }}</div>
                            </div>
                        </el-form-item>
                        <el-form-item label="借款描述" prop="description">
                            <div class="preview">{{ addForm.description }}</div>
                        </el-form-item>
                    </el-form>
                </div>
            </div>
            <el-divider style="margin: 0;" v-if="newFormItem.length"></el-divider>
            <div class="drawer-content">
                <div :class="{ 'oa-form': true, 'params-form-gray': true, disable: !isNew }" v-if="newFormItem.length">
                    <form-render ref="formRenderRef" :forms="newFormItem" v-model="formData" />
                </div>
            </div>
            <template #footer v-if="isNew">
                <div class="footer-btn">
                    <el-button @click="visible = false">取消</el-button>
                    <el-button type="primary" @click="confirm">确定</el-button>
                </div>
            </template>
        </el-drawer>
        <el-dialog v-model="accountVisible" width="400" center align-center :show-close="false" @close="closeAccount">
            <template #title>
                <custom-title title="新建支付账号" />
            </template>
            <el-form :model="accountForm" label-width="auto" ref="accountFormRef" :rules="accountRules">
                <el-form-item label="支付方式" prop="dictId">
                    <el-select-v2 v-model:model-value="accountForm.dictId" filterable remote
                        :remote-method="remoteMethod" clearable :options="payTypeList"
                        :props="{ label: 'dictName', value: 'dictId' }" placeholder="请输入名称" />
                </el-form-item>
                <el-form-item label="账号" prop="account">
                    <el-input v-model="accountForm.account" placeholder="请输入账号" />
                </el-form-item>
                <el-form-item label="开户银行" prop="bankName">
                    <el-input v-model="accountForm.bankName" placeholder="请输入开户银行" />
                </el-form-item>
                <el-form-item label="户名" prop="accountName">
                    <el-input v-model="accountForm.accountName" placeholder="请输入户名" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="footer-btn">
                    <el-button @click="accountVisible = false">取消</el-button>
                    <el-button type="primary" @click="addAccount">确定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { Search, RefreshRight } from "@element-plus/icons-vue";
import { getAccount as getAccountList } from "@/apis/oa/index";
import { getLoanList, exportLoan, addLoan, getLoanDetail, addAccount as add} from "@/apis/oa/loan";
import { getFormDetail,getLoanTree } from "@/apis/oa/index";
import { ref, onMounted, computed } from "vue";
import { useRoute } from "vue-router";
import exportExcel from "@/utils/exportExcel";

import { ElMessage } from "element-plus";
import { payTypeDict } from "@/apis/dict/dict";
import { shieldArr } from "@/utils/config";
const route = useRoute();
const accountForm = ref({});
const accountVisible = ref(false);
const visible = ref(false);
const statusList = {
  审批中: "warning",
  处理中: "primary",
  已处理: "success",
  未通过: "danger",
  还款中: "warning",
  未还款: "danger",
  已还款: "success",
  待付款: "primary"
};
const newFormItem = computed(() => formItemsData.value.filter(v => !shieldArr.includes(v.title)));
const addFormRef = ref(null);
const formRenderRef = ref(null);
const accountFormRef = ref(null);
const formData = ref({});
const formItemsData = ref([]);
const params = ref({
  overdue: false,
  billNoteId: route.query.billNoteId || route.query.code
});
const query = ref({
  current: 1,
  size: 10
});
const payType = ref("");
const total = ref(0);
const isNew = ref(false);
const addForm = ref({});
const data = ref([]);
const accountList = ref([]);
const openDrawer = async item => {
  if (item.billNoteId) {
    isNew.value = false;
    const res = await getLoanDetail(item.billNoteId);
    addForm.value = res.data;
    const formRes = await getFormDetail(res.data.flowInstanceId);
    formData.value = formRes.data.formData;
    formItemsData.value = formRes.data.formItems.map(v => ({ ...v, props: { ...v.props, disabled: true } }));
  } else {
    isNew.value = true;
  }
  visible.value = true;
};
const closeAccount = () => {
  accountFormRef.value.resetFields();
};
const accountRules = {
  account: [
    { required: true, message: "请输入账号", trigger: "blur" },
    { max: 20, message: "开户银行不能超过20个字符", trigger: "blur" }
  ],
  dictId: [{ required: true, message: "请选择支付方式", trigger: "blur" }],
  accountName: [{ max: 20, message: "户名不能超过20个字符", trigger: "blur" }],
  bankName: [{ max: 20, message: "开户银行不能超过20个字符", trigger: "blur" }]
};
const rules = {
  billCategoryId: [{ required: true, message: "请选择借款分类", trigger: "change" }],
  money: [
    { required: true, message: "请输入借款金额", trigger: "blur" },
    { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: "请输入正确的金额", trigger: "blur" }
  ],
  partnerAccountId: [{ required: true, message: "请选择支付账号", trigger: "change" }],
  description: [
    { required: true, message: "请输入借款描述", trigger: "blur" },
    { max: 100, message: "借款描述不能超过100个字符", trigger: "blur" }
  ],
  repaymentDate: [{ required: true, message: "请选择还款日期", trigger: "change" }]
};
const close = () => {
  addForm.value = {};
  formItemsData.value = [];
  formData.value = {};
  addFormRef.value?.resetFields();
  formRenderRef.value?.resetForm();
  accountVisible.value = false;
  payType.value = "";
};
const reset = () => {
  params.value = {};
  init();
};
const payTypeList = ref([]);
const remoteMethod = async dictName => {
  const res = await payTypeDict({ status: 1, dictName });
  payTypeList.value = res.data;
};
const getParmas = () => {
  let startCreateTime = "";
  let endCreateTime = "";
  if (params.value.date) {
    startCreateTime = params.value.date[0] + " " + "00:00:00";
    endCreateTime = params.value.date[1] + " " + "23:59:59";
  } else {
    startCreateTime = undefined;
    endCreateTime = undefined;
  }
  return { ...params.value, startCreateTime, endCreateTime };
};
const init = async () => {
  const res = await getLoanList(query.value, getParmas());
  total.value = res.data.total;
  data.value = res.data.list;
};
const loanTree = ref([]);
const getTree = async () => {
  const res = await getLoanTree();
  loanTree.value = res.data.filter(v => v.type == 2);
};
const addAccount = () => {
  accountFormRef.value.validate(async valid => {
    if (valid) {
      const res = await add({ ...accountForm.value, status: 1 });
      if (res.code == 200) {
        accountVisible.value = false;
        ElMessage.success("添加成功");
        getAccount();
      }
    }
  });
};
const excel = async () => {
  const res = await exportLoan(getParmas());
  exportExcel(res, "借款列表");
};
const verify = () => {
  let arr = [];
  arr.push(
    new Promise(resolve => {
      addFormRef.value.validate(valid => {
        resolve(valid);
      });
    })
  );
  arr.push(
    new Promise(resolve => {
      formRenderRef.value.submitForm(valid => {
        resolve(valid);
      });
    })
  );
  return Promise.all(arr);
};
const confirm = async () => {
  if ((await verify()).every(v => v)) {
    const res = await addLoan({
      ...addForm.value,
      fromData: formData.value,
      billCategoryId: addForm.value.billCategoryId[addForm.value.billCategoryId.length - 1]
    });
    if (res.code == 200) {
      init();
      ElMessage.success("添加成功");
      visible.value = false;
    }
  }
};
const getAccount = async () => {
  const res = await getAccountList();
  accountList.value = res.data;
};
onMounted(() => {
  init();
  getTree();
  getAccount();
  remoteMethod();
});
</script>

<style lang="scss" scoped>
$border: 1px solid #dcdfe6;

.params-form {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  column-gap: 50px;

  > div:last-child {
    grid-column: 3;

    ::v-deep(.el-form-item__content) {
      display: flex;
      justify-content: end;
    }
  }
}

.table-add {
  margin: 20px 0;
  display: flex;
  justify-content: space-between;

  ::v-deep(.el-checkbox__inner) {
    border-radius: 50% !important;
    transform: scale(1.2);
  }
}

.table {
  border: $border;

  ::v-deep(.el-table tr) {
    height: 46px;
    td,
    th {
      border-bottom: $border !important;
    }
    td:last-child {
      border-left: $border;
    }
    .cell {
      display: flex;
      justify-content: center;
    }
  }
  ::v-deep(.el-table.is-scrolling-left .el-table-fixed-column--right.is-first-column:before) {
    box-shadow: none;
  }
  ::v-deep(.el-table thead tr) {
    background: #f2f6fc;
    > th {
      background: transparent;
      text-align: center;
    }
    th:last-child {
      border-left: $border;
    }
    .el-table-fixed-column--right {
      background: #f2f6fc;
    }
  }

  ::v-deep(.el-table tbody tr:nth-child(even)) {
    background: #f2f6fc;
  }

  ::v-deep(.el-table tbody tr:last-child) {
    td {
      border-bottom: none !important;
    }
  }

  ::v-deep(.el-table__inner-wrapper) {
    &::before {
      display: none;
    }
  }
}

::v-deep(.el-drawer.rtl) {
  border-radius: 20px 0 0 20px;
  width: 500px !important;
}

::v-deep(.el-drawer__body) {
  padding: 0 !important;
}

.drawer-content {
  padding: 20px;
  padding-bottom: 0;

  .title-box {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .el-icon {
      font-size: 20px;
    }
  }

  .form-item-space {
    flex: 1;
    display: flex;
    gap: 10px;
  }

  .oa-form {
    max-height: calc(100vh - 380px);
    background: #f6f8fa;
    width: 460px;
    padding: 10px;
    box-sizing: border-box;
  }

  &:first-child {
    .params-form-gray {
      padding-bottom: 20px;
      margin-bottom: 20px;
    }
  }

  ::v-deep(.el-select__wrapper) {
    box-sizing: border-box;
  }
}

.footer-btn {
  display: flex;
  justify-content: center;
  gap: 10px;
}

.overdue {
  color: red;
}

.preview {
  word-break: break-all;
  word-wrap: break-word;
  overflow-wrap: break-word;
}
</style>
@/apis/oa
